import {PathImporter} from '../paths'
import utils from '../utils'
import shapeFile from './index.js'
import {ShpReader} from './index.js'

// Read Shapefile data from a file, ArrayBuffer or Buffer
// @shp, @shx: filename or buffer
function importShp(shp, shx, opts) {
  const reader = new ShpReader(shp, shx)
  const shpType = reader.type()
  const type = shapeFile.translateShapefileType(shpType)
  const importOpts = utils.defaults({
        type: type,
        reserved_points: Math.round(reader.header().byteLength / 16)
      }, opts)
  const importer = new PathImporter(importOpts)

  if (!shapeFile.isSupportedShapefileType(shpType)) {
    // stop("Unsupported Shapefile type:", shpType)
    utils.error(`Unsupported Shapefile type:${shpType}`)
  }
  // if (ShpType.isZType(shpType)) {
  //   message("Warning: Shapefile Z data will be lost.")
  // } else if (ShpType.isMType(shpType)) {
  //   message("Warning: Shapefile M data will be lost.")
  // }

  // TODO: test cases: null shape; non-null shape with no valid parts
  reader.forEachShape(function(shp) {
    importer.startShape()
    if (shp.isNull) {
      // skip
    } else if (type == 'point') {
      importer.importPoints(shp.readPoints())
    } else {
      shp.stream(importer)
      // shp.stream2(importer);
    }
  })

  return importer.done()
}
export default importShp
